﻿public class WeChatAuthMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<WeChatAuthMiddleware> _logger;

    //如下开通的均跳过检查；如/api/auth/check-session，也跳过检查，即ShouldSkipAuthCheck=true;
    private readonly string[] _excludedPaths = new[]
    {
        "/api/auth",           // 认证相关接口
        "/css/",               // 静态资源
        "/js/",
        "/images/",
        "/lib/",
        "/favicon.ico",        // 网站图标
        "/health",             // 健康检查
        "/.well-known/",       // 证书验证
        "/auth-callback.html"  // 授权回调页面
    };

    public WeChatAuthMiddleware(RequestDelegate next, ILogger<WeChatAuthMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context,IWeChatAuthService weChatAuthService,ISessionManager sessionManager)
    {
        var path = context.Request.Path;

        if (await ShouldSkipAuthCheck(path))
        {
            await _next(context);
            return;
        }

        if (!await IsUserAuthenticated(context, sessionManager))
        {
            await HandleUnauthorizedAccess(context, weChatAuthService, path);
            return;
        }

        await SetUserContext(context, sessionManager);
        await _next(context);
    }

    
    /// <summary>
    /// 掉过授权检查；
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    private async Task<bool> ShouldSkipAuthCheck(PathString path)
    {
        var pathString = path.Value ?? "";

        _logger.LogDebug("检查路径排除: {Path}", pathString);

        foreach (var excludedPath in _excludedPaths)
        {
            // 精确匹配或前缀匹配
            if (pathString.Equals(excludedPath, StringComparison.OrdinalIgnoreCase) ||
                pathString.StartsWith(excludedPath, StringComparison.OrdinalIgnoreCase))
            {
                _logger.LogDebug("路径匹配排除规则: {ExcludedPath}", excludedPath);
                return true;
            }
        }

        // 特殊处理：检查是否是授权回调
        if (pathString.Contains("/auth/callback") || pathString.Contains("auth-callback"))
        {
            _logger.LogDebug("授权回调路径，跳过认证");
            return true;
        }

        _logger.LogDebug("路径需要认证检查");
        return false;
    }



    private async Task<bool> IsUserAuthenticated(HttpContext context, ISessionManager sessionManager)
    {
        var sessionId = context.Request.Cookies["ltweixin_session"];

        if (string.IsNullOrEmpty(sessionId))
        {
            _logger.LogDebug("未找到会话Cookie");
            return false;
        }

        var isValid = await sessionManager.ValidateSessionAsync(sessionId);

        if (!isValid)
        {
            _logger.LogDebug("会话验证失败: {SessionId}", sessionId);
        }

        return isValid;
    }

    private async Task HandleUnauthorizedAccess(HttpContext context, IWeChatAuthService weChatAuthService, PathString path)
    {
        //此为请求的api地址；或需要活动前台页面程序，则必须将前台html文件明天通过前台参数明确带入后台才行；
        var returnUrl = BuildReturnUrl(context);

        //未授权全部导航至，默认首页index.html
        returnUrl = $"{context.Request.Scheme}://{context.Request.Host}/index.html";


        



        var authorizationUrl = await weChatAuthService.GenerateAuthUrlAsync(returnUrl);

        if (path.StartsWithSegments("/api"))
        {
            //await HandleApiUnauthorized(context, authorizationUrl);
            context.Response.StatusCode = 401;
            await context.Response.WriteAsJsonAsync(new
            {
                message = "未授权访问401",
                authUrl = authorizationUrl
            });

            _logger.LogInformation("API请求未授权，返回401状态码");


        }
        else
        {
            context.Response.Redirect(authorizationUrl);
            _logger.LogInformation("页面请求未授权，重定向到微信授权页面");

            //await HandlePageUnauthorized(context, authorizationUrl);
        }
    }

   

    //private async Task HandleApiUnauthorized(HttpContext context, string authUrl)
    //{
    //    context.Response.StatusCode = 401;
    //    await context.Response.WriteAsJsonAsync(new
    //    {
    //        code = 401,
    //        message = "未授权访问",
    //        requireAuth = true,
    //        authUrl = authUrl
    //    });

    //    _logger.LogInformation("API请求未授权，返回401状态码");
    //}

    //private async Task HandlePageUnauthorized(HttpContext context, string authUrl)
    //{
    //    context.Response.Redirect(authUrl);
    //    _logger.LogInformation("页面请求未授权，重定向到微信授权页面");
    //}

    private async Task SetUserContext(HttpContext context, ISessionManager sessionManager)
    {
        var sessionId = context.Request.Cookies["ltweixin_session"];
        var userSession = await sessionManager.GetSessionAsync(sessionId);

        if (userSession != null)
        {
            context.Items["UserSession"] = userSession;
            context.Items["OpenId"] = userSession.OpenId;
            context.Items["UserInfo"] = userSession.UserInfo;

            _logger.LogDebug("设置用户上下文: OpenId={OpenId}", userSession.OpenId);
        }
    }

    private string BuildReturnUrl(HttpContext context)
    {
        return $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
    }
}